import axios from "axios";
import { load } from "cheerio";
import path from "path";
import fs from "fs";

// 获取页面内容
async function grabPage(url) {
  const data = await request(url).catch((error) => {
    console.log("[抓取错误]:", error.message, url);
  });
  return load(data);
}
grabPage("https://www.hm08.lol/photos-view-id-20138233.html");

// 下载图片
async function downloadImage(url, index) {
  const data = await request(url, "GET", "stream");
  // 确保存储目录存在
  const directory = "./axiosIMG";
  if (!fs.existsSync(directory)) {
    fs.mkdirSync(directory);
  }
  // 写入图片文件
  const filePath = path.join(directory, `image_${index}.jpg`);
  const fileStream = fs.createWriteStream(filePath);
  data.pipe(fileStream);

  // 监听文件流事件
  fileStream.on("error", (error) => {
    console.error(`[写入错误] image_${index} to disk:`, error);
  });
  fileStream.on("finish", () => {
    console.log(`Image_${index} 下载成功!`);
  });
}

// 发送请求
async function request(url, method = "GET", responseType) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method,
      responseType,
      proxy: {
        host: "127.0.0.1",
        port: 33210,
      },
    })
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        console.error("error", error);
        reject(error);
      });
  });
}

export { grabPage };
